package com.sls.nzdapplication.ui.activity;

import static com.hjq.permissions.XXPermissions.REQUEST_CODE;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.Settings;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.alibaba.fastjson.JSONObject;
import com.sls.nzdapplication.R;
import com.sls.nzdapplication.app.MySharedPreferences;
import com.sls.nzdapplication.entity.AuthorizationEntity;
import com.sls.nzdapplication.ui.activity.user.LoggedInUserView;
import com.sls.nzdapplication.ui.activity.user.LoginFormState;
import com.sls.nzdapplication.ui.activity.user.LoginResult;
import com.sls.nzdapplication.ui.activity.user.LoginViewModel;
import com.sls.nzdapplication.ui.activity.user.LoginViewModelFactory;
import com.sls.nzdapplication.util.DeviceUtils;
import com.sls.nzdapplication.util.IPAddressHelper;

import java.io.File;
import java.security.NoSuchAlgorithmException;

import es.dmoral.toasty.Toasty;
import me.jessyan.autosize.internal.CustomAdapt;


public class LoginActivity extends AppCompatActivity implements CustomAdapt {

    private LoginViewModel loginViewModel;

    private MySharedPreferences mySharedPreferences;

    private EditText usernameEditText;

    private EditText passwordEditText;

    private EditText serverEditText;


    private EditText serialEditView;

    private EditText macCodeView;

    private ProgressBar loadingProgressBar;

    private EditText loginCodeEditView;

    private EditText peopleEditView;

    private EditText phoneEditView;

    private EditText emailEditView;


    private Switch loginTypeView;

    private boolean islocalLogin = true;

    AuthorizationEntity authorizationEntity = new AuthorizationEntity();

    @SuppressLint("MissingInflatedId")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        if (Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
        loginViewModel = new ViewModelProvider(this, new LoginViewModelFactory())
                .get(LoginViewModel.class);

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);
        }

        peopleEditView = findViewById(R.id.peopleName);
        phoneEditView = findViewById(R.id.phone);
        emailEditView = findViewById(R.id.email);

        peopleEditView.setHintTextColor(getResources().getColor(R.color.gsp_loc_selected));
        phoneEditView.setHintTextColor(getResources().getColor(R.color.gsp_loc_selected));
        emailEditView.setHintTextColor(getResources().getColor(R.color.gsp_loc_selected));
        //软件名称
        authorizationEntity.setDictLable("营配2.0");
//        //软件版本
        authorizationEntity.setVersion(DeviceUtils.getVersionName(getApplicationContext()));
//        //用户类型
        authorizationEntity.setUserTypeDic("0");
//        //ip地址
        authorizationEntity.setIp(IPAddressHelper.getIPAddress(getApplicationContext()));
        authorizationEntity.setHardwareCode(getAndroidId(this));
        serialEditView = findViewById(R.id.serialNumber);
        serialEditView.setVisibility(View.GONE);

        usernameEditText = findViewById(R.id.username);
        passwordEditText = findViewById(R.id.password);
        serverEditText = findViewById(R.id.server_address);

        macCodeView = findViewById(R.id.mac_code);
//        System.err.println(DeviceUtils.getUUid());

        serverEditText.setVisibility(View.GONE);
        serverEditText.setText("http://122.96.144.125:9527");
        final Button loginButton = findViewById(R.id.login);
        final Button getCodeButton = findViewById(R.id.getCode);

        loadingProgressBar = findViewById(R.id.loading);
        loginTypeView = findViewById(R.id.login_type);
        loginCodeEditView = findViewById(R.id.local_code);
        loginCodeEditView.setHintTextColor(getResources().getColor(R.color.gsp_loc_selected));
        if (islocalLogin) {
            loginButton.setEnabled(true);
            getCodeButton.setEnabled(true);
        }
        loginTypeView.setVisibility(View.INVISIBLE);

        loginTypeView.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                islocalLogin = b;
                if (b) {
                    loginButton.setEnabled(true);
                    getCodeButton.setEnabled(true);
                    usernameEditText.setVisibility(View.INVISIBLE);
                    passwordEditText.setVisibility(View.INVISIBLE);
                    serverEditText.setVisibility(View.INVISIBLE);
                    macCodeView.setVisibility(View.VISIBLE);
                    loginCodeEditView.setVisibility(View.VISIBLE);
                } else {
                    loginButton.setEnabled(false);
                    getCodeButton.setEnabled(false);
                    usernameEditText.setVisibility(View.VISIBLE);
                    passwordEditText.setVisibility(View.VISIBLE);
//                    serverEditText.setVisibility(View.VISIBLE);
                    macCodeView.setVisibility(View.INVISIBLE);
                    loginCodeEditView.setVisibility(View.INVISIBLE);
                }
            }
        });

        mySharedPreferences = new MySharedPreferences(getApplicationContext());

        loginViewModel.getLoginFormState().observe(this, new Observer<LoginFormState>() {
            @Override
            public void onChanged(@Nullable LoginFormState loginFormState) {
                if (loginFormState == null) {
                    return;
                }
                loginButton.setEnabled(loginFormState.isDataValid());

                if (loginFormState.getUsernameError() != null) {
                    usernameEditText.setError(getString(loginFormState.getUsernameError()));
                }
                if (loginFormState.getPasswordError() != null) {
                    passwordEditText.setError(getString(loginFormState.getPasswordError()));
                }
                if (loginFormState.getServerError() != null) {
                    passwordEditText.setError(getString(loginFormState.getServerError()));
                }
            }
        });

        loginViewModel.getLoginResult().observe(this, new Observer<LoginResult>() {
            @Override
            public void onChanged(@Nullable LoginResult loginResult) {
                if (loginResult == null) {
                    return;
                }
                loadingProgressBar.setVisibility(View.GONE);
                if (loginResult.getError() != null) {
                    showLoginFailed(loginResult.getError());
                }
                if (loginResult.getSuccess() != null) {
                    updateUiWithUser(loginResult.getSuccess());
                }
                setResult(Activity.RESULT_OK);

                //Complete and destroy login activity once successful
                finish();
            }
        });

        TextWatcher afterTextChangedListener = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // ignore
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // ignore
            }

            @Override
            public void afterTextChanged(Editable s) {
                loginViewModel.loginDataChanged(usernameEditText.getText().toString(),
                        passwordEditText.getText().toString(), serverEditText.getText().toString());
            }
        };
        usernameEditText.addTextChangedListener(afterTextChangedListener);
        passwordEditText.addTextChangedListener(afterTextChangedListener);
        serverEditText.addTextChangedListener(afterTextChangedListener);
        passwordEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    LoginTask loginTask = new LoginTask(getApplicationContext());
                    loginTask.execute(usernameEditText.getText().toString(),
                            passwordEditText.getText().toString(), serverEditText.getText().toString());
                }
                return false;
            }
        });


        loginCodeEditView.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    localLogin(loginCodeEditView.getText().toString());
                }
                return false;
            }
        });


        getCodeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                boolean allValid = true;
                // 获取输入框内容
                String peopleName = peopleEditView.getText().toString();
                String phone = phoneEditView.getText().toString();
                String email = emailEditView.getText().toString();

                // 验证并检查用户名
                if (!verifyUserName(peopleName)) {
                    allValid = false;
                }

                // 验证并检查电话号码
                if (!verifyPhone(phone)) {
                    allValid = false;
                }

                // 验证并检查电子邮件
                if (!verifyEmail(email)) {
                    allValid = false;
                }

                if (authorizationEntity.getIp().equals("")) {
                    Toasty.error(getApplicationContext(), "获取设备IP地址失败，请打开局域网或移动网络", Toast.LENGTH_LONG, true).show();
                    allValid = false;
                }
                if (authorizationEntity.getVersion().equals("")) {
                    Toasty.error(getApplicationContext(), "获取软件版本失败", Toast.LENGTH_LONG, true).show();
                    allValid = false;
                }
                if (authorizationEntity.getHardwareCode().equals("")) {
                    Toasty.error(getApplicationContext(), "获取设备硬件码失败", Toast.LENGTH_LONG, true).show();
                    allValid = false;
                }
                if (allValid) {
                    authorizationEntity.setUserName(peopleName);
                    authorizationEntity.setPhone(phone);
                    authorizationEntity.setEmail(email);
                    //生成之前先删除旧的机器码
                    DeviceUtils.deleteAuth();
                    macCodeView.setText(DeviceUtils.getUUid(authorizationEntity));
                }
            }
        });

        loginButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (!islocalLogin) {
                    LoginTask loginTask = new LoginTask(getApplicationContext());
                    loginTask.execute(usernameEditText.getText().toString(),
                            passwordEditText.getText().toString(), serverEditText.getText().toString());
                } else {
                    localLogin(loginCodeEditView.getText().toString());
                }

            }
        });
        initLogin();
    }

    private boolean verifyUserName(String userName) {
        if (userName.isEmpty()) {
            Toasty.error(LoginActivity.this, "请输入用户名", Toast.LENGTH_LONG, true).show();
            return false;
        }

        String chinesePattern = "^[\\u4e00-\\u9fa5]{2,4}$";
        if (!userName.matches(chinesePattern)) {
            Toasty.error(LoginActivity.this, "请输入二到四个字的中文名称", Toast.LENGTH_LONG, true).show();
            return false;
        }

        return true;
    }

    private boolean verifyPhone(String phone) {
        if (phone.isEmpty()) {
            Toasty.error(LoginActivity.this, "请输入手机号码", Toast.LENGTH_LONG, true).show();
            return false;
        }

        String phonePattern = "^1[3-9]\\d{9}$";
        if (!phone.matches(phonePattern)) {
            Toasty.error(LoginActivity.this, "请输入正确的手机号码", Toast.LENGTH_LONG, true).show();
            return false;
        }
        return true;
    }

    private boolean verifyEmail(String email) {
        if (email.isEmpty()) {
            Toasty.error(LoginActivity.this, "请输入邮箱地址", Toast.LENGTH_LONG, true).show();
            return false;
        }

        if (!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
            Toasty.error(LoginActivity.this, "请输入正确的邮箱地址", Toast.LENGTH_LONG, true).show();
            return false;
        }
        return true;
    }

    public String getAndroidId(Context context) {
        return Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
    }

    private void initLogin() {
//        deleteDatabase("xj.db");
        if (!"".equals(mySharedPreferences.getUserValue("token"))) {
            int codeinfo = DeviceUtils.isAuthorized(mySharedPreferences.getUserValue("token"), getApplicationContext());
            if (codeinfo == 2) {
                Toasty.error(LoginActivity.this, "注册码已过期,请重新注册", Toast.LENGTH_LONG, true).show();
                DeviceUtils.deleteAuth();
            } else {
                startActivity(new Intent(LoginActivity.this, MyActivity.class));
                this.finish();
            }

        }
    }

    private void localLogin(String code) {
        if (code.equals("")) {
            Toasty.error(LoginActivity.this, "注册码不允许为空", Toast.LENGTH_LONG, true).show();
            return;
        }
        int codeinfo = DeviceUtils.isAuthorized(code, getApplicationContext());
        if (codeinfo == -1) {
            Toasty.error(LoginActivity.this, "注册码不正确", Toast.LENGTH_LONG, true).show();
            return;
        } else if (codeinfo == 1) {
            Toasty.error(LoginActivity.this, "注册码不匹配", Toast.LENGTH_LONG, true).show();
            return;
        } else if (codeinfo == 2) {
            Toasty.error(LoginActivity.this, "注册码已过期", Toast.LENGTH_LONG, true).show();
            return;
        }else if (codeinfo == 3){
            Toasty.error(LoginActivity.this, "注册码未到生效时间", Toast.LENGTH_LONG, true).show();
            return;
        }else if (codeinfo == 4){
            Toasty.error(LoginActivity.this, "注册码与APP不匹配", Toast.LENGTH_LONG, true).show();
        }
        mySharedPreferences.clearUserInfo();
        mySharedPreferences.saveUserInfo("本地操作员", code, "local");
        startActivity(new Intent(LoginActivity.this, MyActivity.class));
//        startActivity(new Intent(com.sls.autoc.application.ui.activity.LoginActivity.this, MapActivity.class));
        this.finish();
    }

    private void updateUiWithUser(LoggedInUserView model) {
        String welcome = getString(R.string.welcome) + model.getDisplayName();
        // TODO : initiate successful logged in experience
        Toast.makeText(getApplicationContext(), welcome, Toast.LENGTH_LONG).show();
    }

    private void showLoginFailed(@StringRes Integer errorString) {
        Toast.makeText(getApplicationContext(), errorString, Toast.LENGTH_SHORT).show();
    }

    @Override
    public boolean isBaseOnWidth() {
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            return true;//根据宽度适配
        } else {
            return false;//根据高度适配
        }
    }

    @Override
    public float getSizeInDp() {
        // 横屏下的高度不就是竖屏的宽度吗,所以统一返回宽度即可
        return 500;
    }


    class LoginTask extends AsyncTask<String, Integer, JSONObject> {
        private Context mContext;
        private String server;


        public LoginTask(Context context) {
            this.mContext = context;
        }

        @Override
        protected void onPreExecute() {
            loadingProgressBar.setVisibility(View.VISIBLE);
        }

        @Override
        protected JSONObject doInBackground(String... strings) {
            server = strings[2];
            return loginViewModel.login(strings[0], strings[1], strings[2]);
        }

        @Override
        protected void onPostExecute(JSONObject jsonObject) {
            super.onPostExecute(jsonObject);
            if (null != jsonObject.getString("id")) {
                mySharedPreferences.saveUserInfo(jsonObject.getString("username"), jsonObject.getString("token"), server);
                startActivity(new Intent(LoginActivity.this, MyActivity.class));
                LoginActivity.this.finish();
            } else {
                loadingProgressBar.setVisibility(View.GONE);

//                Toasty.error(mContext, "登录失败！", Toast.LENGTH_SHORT,true).show();
            }
        }
    }


}